package com.koron.tool.frame;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;
import javax.swing.border.TitledBorder;

import com.koron.common.CommonAssistant;
import com.koron.tool.Constant;
import com.koron.tool.MainFrame;
import com.koron.tool.frame.bean.InsertBean;
import com.koron.ui.MutableGridLayout;

@SuppressWarnings("serial")
public class InsertPanel extends JPanel {
	private InsertBean bean;
	private JTextArea jtaSQL = new JTextArea();
	private JTextArea jtaMemo = new JTextArea();
	private JTextArea jtaMethod = new JTextArea();
	private JTextField txtId = new JTextField();
	private JTextField txtParameterType = new JTextField();
	private JComboBox<String> cbxUseGeneratedKeys = new JComboBox<>(new String[] { "false", "true" });
	private JTextField txtKeyProperty = new JTextField();

	private ResourceBundle resourceBuddle = ResourceBundle.getBundle(MainFrame.RESOURCEBUDDLE, getLocale());

	public InsertPanel(InsertBean bean) {
		super();
		MutableGridLayout layout = new MutableGridLayout(4, 6, 5, 5);
		layout.merge(0, 2, 3, 2);
		layout.merge(0, 3, 3, 3);
		layout.merge(0, 4, 3, 4);
		layout.merge(0, 5, 1, 5);
		layout.merge(2, 5, 3, 5);
		layout.setHeight(0, 20);
		layout.setHeight(1, 20);
		layout.setHeight(2, 80);
		layout.setHeight(3, 80);
		layout.setHeight(5, 20);
		layout.setWidth(0, 100);
		layout.setWidth(2, 100);
		this.setLayout(layout);
		this.bean = bean;
		add(new JLabel("ID"));
		add(txtId);
		add(new JLabel(resourceBuddle.getString("InputType")));
		add(txtParameterType);
		add(new JLabel(resourceBuddle.getString("IfReturnId")));
		add(cbxUseGeneratedKeys);
		add(new JLabel(resourceBuddle.getString("IdField")));
		add(txtKeyProperty);
		JScrollPane jsp = new JScrollPane(jtaMemo);
		jsp.setBorder(new TitledBorder(resourceBuddle.getString("Memo")));
		add(jsp);
		jsp = new JScrollPane(jtaMethod);
		jsp.setBorder(new TitledBorder(resourceBuddle.getString("DefinedMethod")));
		add(jsp);
		CommonAssistant.getMethodAssis().bind(jtaMethod, null);
		CommonAssistant.getSqlAssis().bind(jtaSQL, null);
		jtaSQL.setTabSize(4);
		jtaMemo.setTabSize(4);

		jsp = new JScrollPane(jtaSQL);
		jsp.setBorder(new TitledBorder(resourceBuddle.getString("SQLContext")));
		add(jsp);
		SelectPanel.bindMethod(txtId, jtaMethod);
		JButton btnSave = new JButton(resourceBuddle.getString("Save"));
		btnSave.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					save();
					JOptionPane.showInternalMessageDialog(((JButton) e.getSource()).getRootPane(), "数据已保存");
				} catch (IOException e1) {
					JOptionPane.showInternalMessageDialog(((JButton) e.getSource()).getRootPane(), e1.getMessage());
				}
			}
		});

		add(btnSave);
		JButton btnReset = new JButton(resourceBuddle.getString("Reset"));
		btnReset.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				reset();
			}
		});
		add(btnReset);
		reset();
	}

	private void reset() {
		txtId.setText(bean.getId());
		txtParameterType.setText(bean.getParameterType());
		if (bean.getUseGeneratedKeys() != null)
			cbxUseGeneratedKeys.setSelectedItem(bean.getUseGeneratedKeys());
		else
			cbxUseGeneratedKeys.setSelectedItem("false");
		txtKeyProperty.setText(bean.getKeyProperty());
		jtaSQL.setText(bean.getContent());
		try {
			File file = new File(MainFrame.config.get(Constant.SRCPATH) + File.separatorChar
					+ bean.getNameSpace().replace('.', '/') + ".java");
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),
					MainFrame.config.get(Constant.ENCODE)), 1024);
			String tmp = null;
			StringBuilder sb = new StringBuilder();
			while ((tmp = br.readLine()) != null) {
				sb.append(tmp).append("\n");
			}
			if (sb.length() > 0)
				sb.deleteCharAt(sb.length() - 1);
			br.close();

			Pattern p = Pattern.compile("(/\\*\\*([^;]*?)\\*/)?\\s*(public [^;{]*" + bean.getId() + "\\s*\\([^;]*;)");
			Matcher m = p.matcher(sb);
			if (m.find()) {
				jtaMemo.setText(m.group(2));
				jtaMethod.setText(m.group(3));
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	private void save() throws IOException {
		String oldId = bean.getId();
		bean.setId(txtId.getText());
		bean.setParameterType(txtParameterType.getText());
		bean.setContent(jtaSQL.getText());
		bean.setUseGeneratedKeys(cbxUseGeneratedKeys.getSelectedItem().toString());
		bean.setKeyProperty(txtKeyProperty.getText());
		saveJavaFile(oldId);
		bean.saveToXml(oldId);
	}

	private void saveJavaFile(String oldId) throws IOException {
		File file = new File(MainFrame.config.get(Constant.SRCPATH) + File.separatorChar
				+ bean.getNameSpace().replace('.', '/') + ".java");
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),
				MainFrame.config.get(Constant.ENCODE)), 1024);

		String tmp = null;
		StringBuilder sb = new StringBuilder();
		while ((tmp = br.readLine()) != null) {
			sb.append(tmp).append("\n");
		}
		if (sb.length() > 0)
			sb.deleteCharAt(sb.length() - 1);
		br.close();

		Pattern p = Pattern.compile("(/\\*\\*([^;]*?)\\*/)?\\s*(public [^;{]*" + oldId + "\\s*\\([^;]*;)");
		Matcher m = p.matcher(sb);
		if (m.find()) {
			sb.replace(m.start(3), m.end(3), jtaMethod.getText());
			if (m.start(1) > -1)
				sb.replace(m.start(2), m.end(2), jtaMemo.getText());
			else
				sb.insert(m.start(3), "/**\n" + jtaMemo.getText() + "\n*/\n");
		}
		Writer fw = new PrintWriter(file, MainFrame.config.get(Constant.ENCODE));
		fw.write(sb.toString());
		fw.close();
	}
}
